package com.travel.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.travel.mapper.MemberMapper;
import com.travel.dto.UserLoginRequestDto;
import com.travel.pojo.Member;
import com.travel.member.vo.LoginVo;
import com.travel.result.PageResult;
import com.travel.service.WechatService;
import com.travel.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.travel.service.IMemberService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: libin
 * Date: 2025/6/9 15:57
 * Description:
 **/
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements IMemberService {


    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private WechatService wechatService;
    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "远方旅人", "山川纪行", "云端漫步", "星海漫游",
            "湖海拾光", "丝路行者", "雨林探秘", "极地探索",
            "古城印记", "海滨逐浪", "山野寻踪", "都市漫游",
            "秘境探险", "光影旅途", "风语者", "时光旅者"
    );
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //获取openid  微信接口获取
        String openid = wechatService.getOpenid(dto.getCode());

        //根据openid查询用户信息
        Member member = getOne(Wrappers.<Member>lambdaQuery().eq(Member::getOpenId, openid));

        //如果用户为空，构建用户，赋值一个openid
        if(ObjectUtil.isEmpty(member)){
            member = Member
                    .builder()
                    .openId(openid)
                    .build();
        }
        //获取用户的手机号  微信接口获取
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //保存或更新用户
        insertOrUpdateFamilyMember(member,phone);

        //生成token返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", member.getId());
        claims.put("userName", member.getName());

        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(member.getName());
        loginVo.setPhone(member.getPhone());
        loginVo.setToken(token);
        loginVo.setRole(member.getRole());

        return loginVo;
    }

    @Override
    public PageResult getUserInfoList(Integer pageNum, Integer pageSize, Member member) {
        // 1. 构建分页对象
        Page<Member> page = new Page<>(pageNum, pageSize);

        // 2. 构建查询条件
        LambdaQueryWrapper<Member> queryWrapper = new LambdaQueryWrapper<>();

        // 3. 判断 member 不为空再添加查询条件
        if (member != null) {
            if (StringUtils.isNotBlank(member.getPhone())) {
                queryWrapper.like(Member::getPhone, member.getPhone());
            }
            if (member.getRole() != null) {
                queryWrapper.eq(Member::getRole, member.getRole());
            }
        }

        // 4. 执行分页查询
        IPage<Member> userPage = memberMapper.selectPage(page, queryWrapper);

        // 5. 转换为 VO 对象（如果没有 VO，就直接使用原始记录）
        List<Member> userVOs = userPage.getRecords();

        // 6. 构建分页结果
        PageResult pageResult = new PageResult();
        pageResult.setRecords(userVOs);
        pageResult.setTotal(userPage.getTotal());

        return pageResult;
    }


    private void insertOrUpdateFamilyMember(Member familyMember, String phone) {

        //判断手机号与数据库的手机号是否一致
        if(ObjectUtil.notEqual(familyMember.getPhone(),phone)){
            familyMember.setPhone(phone);
        }
        //判断是否存在id，如果存在id，则更新，不存在则保存
        if(ObjectUtil.isNotEmpty(familyMember.getId())){
            updateById(familyMember);
            return;
        }
        //获取用户的昵称
        int index = (int)(Math.random() * DEFAULT_NICKNAME_PREFIX.size());
        String nickName = DEFAULT_NICKNAME_PREFIX.get(index) + StringUtils.substring(phone,7,11);
        familyMember.setName(nickName);
        familyMember.setRole(0); // 默认普通用户
        familyMember.setAvatar("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
        //保存
        save(familyMember);

    }
}
